const cp = require('child_process');
const chalk = require('chalk');
const paths = require('../utils/paths');
const argv = require('minimist')(process.argv.slice(2));
console.log(argv)

const logger = {
  error: text => console.log(chalk.redBright(text)),
  warn: text => console.log(chalk.yellowBright(text)),
  success: text => console.log(chalk.green(text)),
  info: text => console.log(chalk.whiteBright(text)),
};

const pub = (qaNum) => {
  logger.info(`正在部署QA${qaNum}...`, 'blueBright');
  const execStr = `fsk-sync -d ./ -r /data/static/QA${qaNum}/${paths.projectName} -h 10.110.15.1 -p qa -u qa --localroot asset-dev --pub`;
  const [command, ...argArr] = execStr.split(' ');
  const ls = cp.spawn(command, argArr);
  ls.stdout.on('data', function (data) {
    logger.success(`QA${qaNum}/${paths.projectName}: success >>> ${data.toString().split(' ')[1]}`);
  });

  ls.stderr.on('data', function (data) {
    logger.error(`\n部署QA${qaNum}失败: \n\n${data} `);
  });

  ls.on('exit', function (code) {
    if(code === 0){
      logger.success(`\n已部署QA${qaNum}\n`);
    }
  });
}
if(argv.qa){
  if(typeof argv.qa === 'number'){
    pub(argv.qa)
  }else{
    const qaArr = argv.qa.split(',');
    for(let qaName of qaArr) {
      if(/\d/g.test(qaName)){
        pub(qaName.replace(/[^\d]/g, ''))
      }else{
        pub(qaName)
      }
    }
  }
} else {
  logger.warn('\n请输入正确的qa参数')
  logger.info('\n例：npm run pub -- --qa 28\n');
}

